package com.itheima.common.exception;

import com.itheima.blog.util.constants.ErrorInfo;
import com.itheima.common.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理Throwable的处理器，做一个兜底处理
     * */
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable e){
        log.error("全局异常处理器，异常堆栈:{}", ExceptionUtils.getStackTrace(e));
        return R.error(ErrorInfo.Msg.SERVER_INTER_ERROR);
    }

    /**
     * 处理BlogException的处理器
     * */
    @ExceptionHandler(BlogException.class)
    public R handleLeadException(BlogException e){
        return R.error(e.getStatus(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     * */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        // 获取所有的异常
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        // 拼接异常字符串
        String msg = allErrors.stream().map(error -> error.getDefaultMessage()).collect(Collectors.joining(";"));
        return R.error(msg);
    }

    /**
     * HttpRequestMethodNotSupportedException
     * */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception){
        return R.error(exception.getMessage());
    }
    @ExceptionHandler(CommonException.class)
    public R handlerHttpRequestMethodNotSupportedException(CommonException exception){
        return R.error(exception.getMessage());
    }
}
